<template>
  <div class="spatial_main_con">
    <div class="spatial_main_title">
      <span>空间查询</span>
    </div>
    <!-- <el-form ref="elForm" :model="form" label-width="0px" >
      <el-form-item >
        <el-radio-group v-model="form.resource">
          <el-radio label="绘制区域"></el-radio>
          <el-radio label="缓冲区查询"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row>
        <el-button icon="el-icon-search" circle></el-button>
        <el-button type="primary" icon="el-icon-edit" circle></el-button>
        <el-button type="success" icon="el-icon-check" circle></el-button>
      </el-row>
      <el-form-item >
        <el-checkbox-group v-model="form.type">
          <el-checkbox label="管线" name="type"></el-checkbox>
          <el-checkbox label="监控点" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
    </el-form> -->

    <div class="radio-btn">
      <div class="hzqy-btn">
        <span @click="changetype(0)">区域查询</span>
      </div>
      <div class="hcqcx-btn">
        <span @click="changetype(1)">缓冲区查询</span>
      </div>
    </div>
    <div class="main-content" style="color: #ffffff" v-if="type == 0">
      <div class="tootipText">
        <div class="tooltipbg"></div>
        <span>请在地图上框选需要查询的范围</span>
      </div>
      <div class="btnGroupHZQY">
        <div @click="getPosition('Polygon')" class="funBtn">画面</div>
        <div @click="clearPositions" class="funBtn">清除</div>
        <div @click="spatialQuery" class="funBtn">查询</div>
      </div>
      <!-- <span @click="getPosition('Polygon')">绘制区域</span>
      <span @click="clearPositions">清除</span>
      <span @click="spatialQuery">查询</span> -->
    </div>
    <!-- <div class="radio-btn" style="color: #ffffff;" v-if="type==1">
      <span @click="getPosition('Polyline')">线</span>
      <span @click="getPosition('Polygon')">面</span>
      <span @click="clearPositions">清除</span>
      <span @click="bufferQuery">查询</span>
    </div> -->
    <div class="main-content" style="color: #ffffff" v-if="type == 1">
      <div class="tootipText">
        <div class="tooltipbg"></div>
        <span>请在地图上框选需要查询的范围</span>
      </div>
      <div class="main_input">
        <el-input v-model="hcfwdata" placeholder="请输入缓冲范围" size="small"  clearable></el-input>
        <div class="i_danwei">米</div>
      </div>
      <div class="btnGroupHZQY">
        <div @click="getPosition('Polyline')" class="funBtn hcqbtn">画线</div>
        <div @click="getPosition('Polygon')" class="funBtn hcqbtn">画面</div>
        <div @click="clearPositions" class="funBtn hcqbtn">清除</div>
        <div @click="bufferQuery(typeselect)" class="funBtn hcqbtn">查询</div>
      </div>
    </div>

    <div class="checkbox-btn-container">
      <!-- <el-checkbox-group v-model="typeList">
        <el-checkbox label="管线" ></el-checkbox>
        <el-checkbox label="监控点"></el-checkbox>
      </el-checkbox-group> -->
    </div>

    <div class="spatial_result">
      <div class="form_item_title">
        <span>查询结果</span>
      </div>

      <!-- <div style="color: #ffffff;">
        管线
        <br>
        <ul v-for="(item,i) in dataline" :key="i">
          <li> <span>{{item.properties.name}} </span> <span>{{item.properties.p_name}}
            </span><span>{{item.properties.UserID}}</span>
          </li>
        </ul>
        监测点
        <br>
        <ul v-for="(item,i) in datapoint" :key="i">
          <li> <span>{{item.properties.device_id}} </span> <span>{{item.properties.address__1}}</span></li>
        </ul>
      </div> -->
      <div class="resultContent">
        <div class="resultTabs">
          <div
            class="guanxianResult"
            :class="resultType == '0' ? 'resultActive' : ''"
            @click="handleClickResult('0')"
          >
            管线
          </div>
          <div
            class="jiancedianResult"
            :class="resultType == '1' ? 'resultActive' : ''"
            @click="handleClickResult('1')"
          >
            监测点
          </div>
        </div>

        <div class="guanxianList" v-show="resultType == '0'">
          <div class="resultItemContent">
            <div class="resultItem" v-for="(item, i) in dataline" :key="i">
              <span>{{ item.properties.name }} </span>
            </div>
          </div>
        </div>
        <div class="jiancedianList" v-show="resultType == '1'">
          <div class="resultItemContent">
            <div class="resultItem" v-for="(item, i) in datapoint" :key="i">
              <span>{{ item.properties.address__1 }} </span>
            </div>
          </div>
        </div>
      </div>
      <!-- <TrendsTable /> -->
    </div>
  </div>
</template>

<script>
import Bus from "@/js/EventBus";
import elSelectTree from "./selectTree.vue";
import * as turf from "@turf/turf";

import { getBoxPointData, getBoxLineData } from "@/api/http";
// import TrendsTable from '@/components/TrendsTable.vue';
// import Bus from "@/js/EventBus";
export default {
  name: "QueryJKD",
  components: {
    elSelectTree,
    // TrendsTable
  },

  data() {
    return {
      type: 0,
      resultType: "0", // 0：管线，1：监测点
      typeselect: "",
      // 整个结果回显
      isShowResult: false,

      typeList: ["管线", "监控点"],

      flagValue: false,
      multiple: true,
      filterText: "", // 输入框关键字过滤
      valueMultiple: [],
      dataline: [
        //   {
        //   properties: {
        //     name: "",
        //     p_name: "",
        //     code: "",
        //   }
        // }
      ],
      datapoint: [
        //   {
        //   name: "",
        //   p_name: "",
        //   code: "",
        // }
      ],
      positions: [],
      hcfwdata: 10,
    };
  },
  mounted() {
    // Bus.$emit("kjcxshujuline", res)
    //     Bus.$emit("kjcxshujupoint", res1)
    // Bus.$on("kjcxshujuline", (e) => {
    //   this.dataline = e
    //   // console.log(e, "=====================================");
    //   // this.gohome(e);
    // });

    // Bus.$on("kjcxshujupoint", (e) => {
    //   this.datapoint = e
    //   // console.log(e, "=====================================");
    //   // this.gohome(e);
    // });
    Bus.$on("positions", (e) => {
      // this.datapoint = e
      // console.log(e, "==============11=======================");
      this.positions = e;
      // this.gohome(e);
    });
  },
  methods: {
    changetype(data) {
      this.type = data;
      this.clearPositions();
    },
    getPosition(type) {
      this.typeselect = type;
      Bus.$emit(type, true, true);
    },

    clearPositions() {
      this.dataline = [];
      this.datapoint = [];
      // this.hcfwdata = 10;
      Bus.$emit("Clear", true);
      Bus.$emit("removedraw", true);
      Bus.$emit("removealllinecolor", true);
    },

    // Bus.$emit("spatialQuery", true);
    //  =======================================空间查询===============================
    async spatialQuery() {
      let pos = [];
      this.positions.forEach((element) => {
        pos.push([element.lng + " " + element.lat]);
        // pos.push(element.lat)
      });

      // 查询管线数据
      let linearrData = this.getPolyognDataLine(pos);
      linearrData.then((res) => {
        // console.log(res, "--------------------");
        this.dataline = res;
        this.dataline.forEach((element) => {
          let idData = {
            UserID: element.properties.UserID,
          };
          Bus.$emit("addlinecolor", JSON.stringify(idData));
          // Bus.$emit("selectyxqu", JSON.stringify(idData));
        });
      });
      // 查询阀门数据
      let pointarrData = this.getPolyognDataPoint(pos);
      pointarrData.then((res) => {
        // console.log(res, "--------------------");
        this.datapoint = res;
        // that.kjcxGetData = res
        // Bus.$emit("kjcxshujupoint", res);
      });

      // return true
    },

    bufferQuery(type) {
      // console.log(type, "typeselect");
      let that = this;
      let pos = [];
      that.positions.forEach((element) => {
        pos.push([element.lng, element.lat]);
        // pos.push(element.lng)
        // pos.push(element.lat)
      });
      // console.log(pos, "pos");

      switch (type) {
        case "Polygon":
          // that.positions.forEach((element) => {
          //   position.push(zhuanhuan(element));
          // });
          // 构成闭环
          // position.push(zhuanhuan(that.positions[0]));
          // console.log(position, "positions=============");

          // pos.push(element.lat)

          that.initPolygonBuffer(pos);
          break;

        case "Polyline":
          // that.positions.forEach((element) => {
          //   position.push(zhuanhuan(element));
          // });
          // console.log(position, "positions=============");
          that.initPolylineBuffer(pos);
          break;

        default:
          break;
      }
      // this.resultType = "0"; // 0：管线，1：监测点
      // // this.isShowResult = true;
      // Bus.$emit("bufferQuery", this.typeselect);
    },
    //初始化线缓冲
    initPolylineBuffer(positions) {
      let that = this;
      let points = positions;
      let degreesArray = this.pointsToDegreesArray(points);
      // let drawPolyline = this.drawPolyline(
      //   Cesium.Cartesian3.fromDegreesArray(degreesArray)
      // );
      // this.tempEntities.push(drawPolyline);

      let polylineF = turf.lineString(points);
      let buffered = turf.buffer(polylineF, that.hcfwdata, { units: "meters" });
      let coordinates = buffered.geometry.coordinates;
      points = coordinates[0];
      degreesArray = this.pointsToDegreesArray(points);
      // console.log(degreesArray, "degreesArray")
      // this.getPolyognData(degreesArray)
      let data = this.BufferData(degreesArray);
      // this.getPolyognData(data)
      let linearrData = this.getPolyognDataLine(data);
      linearrData.then((res) => {
        // console.log(res, "--------------------");
        this.dataline = res;
        this.dataline.forEach((element) => {
          let idData = {
            UserID: element.properties.UserID,
          };
          Bus.$emit("addlinecolor", JSON.stringify(idData));
          // Bus.$emit("selectyxqu", JSON.stringify(idData));
        });
        // 将管线数据存放
        // that.kjcxGetData = res;
        // Bus.$emit("kjcxshujuline", res);
        // //   // 将管线设置颜色
        // res.forEach((element) => {
        //   // console.log(element);
        //   let id = { UserID: element.properties.UserID };
        //   that.addlinesHeightColor(JSON.stringify(id));
        // });
      });
      // 查询阀门数据
      let pointarrData = this.getPolyognDataPoint(data);
      pointarrData.then((res) => {
        // console.log(res, "--------------------");
        this.datapoint = res;
        // that.kjcxGetData = res
        // Bus.$emit("kjcxshujupoint", res);
      });
      this.addBufferPolyogn(Cesium.Cartesian3.fromDegreesArray(degreesArray));
    },
    //初始化面缓冲
    initPolygonBuffer(positions) {
      let that = this;
      let points = positions;

      let degreesArray = this.pointsToDegreesArray(points);
      // Bus.$emit("draw", Cesium.Cartesian3.fromDegreesArray(degreesArray));
      // let drawPolygon = this.drawPolygon(
      //   Cesium.Cartesian3.fromDegreesArray(degreesArray)
      // );

      // that.tempEntities.push(drawPolygon);

      let polygonF = turf.polygon([points]);
      let buffered = turf.buffer(polygonF, that.hcfwdata, { units: "meters" });
      let coordinates = buffered.geometry.coordinates;
      points = coordinates[0];
      degreesArray = this.pointsToDegreesArray(points);
      let data = this.BufferData(degreesArray);

      // this.getPolyognData(data)
      let linearrData = this.getPolyognDataLine(data);
      linearrData.then((res) => {
        this.dataline = res;
        this.dataline.forEach((element) => {
          let idData = {
            UserID: element.properties.UserID,
          };
          Bus.$emit("addlinecolor", JSON.stringify(idData));
          // Bus.$emit("selectyxqu", JSON.stringify(idData));
        });
        // console.log(res, "--------------------");
        // 将管线数据存放
        // that.kjcxGetData = res;
        // Bus.$emit("kjcxshujuline", res);
        // //   // 将管线设置颜色
        // res.forEach((element) => {
        //   // console.log(element);
        //   let id = { UserID: element.properties.UserID };
        //   that.addlinesHeightColor(JSON.stringify(id));
        // });
      });
      // 查询阀门数据
      let pointarrData = this.getPolyognDataPoint(data);
      pointarrData.then((res) => {
        // console.log(res, "--------------------");
        // that.kjcxGetData = res
        // Bus.$emit("kjcxshujupoint", res);
        this.datapoint = res;
      });

      this.addBufferPolyogn(Cesium.Cartesian3.fromDegreesArray(degreesArray));
    },
    //添加缓冲面
    addBufferPolyogn(positions) {
      Bus.$emit("draw", positions);

      // let Polyogn = this.viewer.entities.add({
      //   polygon: {
      //     hierarchy: new Cesium.PolygonHierarchy(positions),
      //     material: Cesium.Color.RED.withAlpha(0.1),
      //     classificationType: Cesium.ClassificationType.BOTH,
      //   },
      // });
      // this.tempEntities.push(Polyogn);
    },
    //格式转换
    pointsToDegreesArray(points) {
      let degreesArray = [];
      points.map((item) => {
        degreesArray.push(item[0]);
        degreesArray.push(item[1]);
      });
      return degreesArray;
    },
    // 缓冲区数据处理
    BufferData(degreesArray) {
      // console.log(degreesArray, "degreesArray")
      // console.log(handleList(degreesArray, 2))
      let a = handleList(degreesArray, 2);
      let c = [];
      a.forEach((element) => {
        c.push(zhuanhua(element));
      });
      // console.log(c, "===========cc===========")
      function handleList(array, subGroupLength) {
        let index = 0;
        const newArray = [];
        while (index < array.length) {
          newArray.push(array.slice(index, (index += subGroupLength)));
        }
        return newArray;
      }

      function zhuanhua(params) {
        return params[0] + " " + params[1];
      }
      return c;
    },
    handleClickResult(value) {
      this.resultType = value;
    },
    handlHZQY() {
      this.type = 0;
      this.getPosition("Polygon");
    },
    // ===========================================获取空间面查询数据==========================================
    async getPolyognDataLine(pos) {
      let that = this;
      // console.log(pos, '==========pos================')
      // 构造空间筛选
      let params = `INTERSECTS(the_geom,SRID=4326;POLYGON((${pos})))`;
      // 请求接口
      const { features: res } = await getBoxLineData(params);
      // const { features: res1 } = await getBoxPointData(params);
      // console.log(res)
      // console.log(features)
      if (!res) {
        return;
      } else {
        return res;
      }
    },
    async getPolyognDataPoint(pos) {
      let that = this;
      // console.log(pos, '==========pos================')
      // 构造空间筛选
      let params = `INTERSECTS(the_geom,SRID=4326;POLYGON((${pos})))`;
      // 请求接口
      // const { features: res } = await getBoxLineData(params);
      const { features: res } = await getBoxPointData(params);
      if (!res) {
        return;
      } else {
        return res;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.radio-btn {
  display: flex;
  flex-direction: row;
  padding: 0 40px;
  justify-content: space-around;
}

.hzqy-btn,
.hcqcx-btn {
  width: 100px;
  height: 28px;
  background: url(../../../assets/panelTree/btn-uncheck.png);
  text-align: center;
  margin: 10px 0 0 10px;
  cursor: pointer;

  span {
    font-family: SourceHanSansCN-Medium;
    font-size: 12px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 28px;
    letter-spacing: 1px;
    color: #00baff;
  }
}

.main-content {
  display: flex;
  flex-direction: column;

  .tootipText {
    display: flex;
    flex-direction: row;
    padding: 10px 20px 0 20px;
    align-items: center;

    .tooltipbg {
      width: 16px;
      height: 16px;
      background: url(../../../assets/panelTree/tooltip.png);
      background-size: 98% 98%;
      margin-right: 10px;
    }

    span {
      font-size: 12px;
      font-weight: normal;
      font-stretch: normal;
      line-height: 28px;
      letter-spacing: 1px;
      color: #95b0c2;
    }
  }

  .btnGroupHZQY {
    width: 280px;
    display: flex;
    flex-direction: row;
    padding: 0 10px 0 10px;
    justify-content: space-between;
    align-items: center;
    // background-color: red;

    .funBtn {
      width: 80px;
      height: 22px;
      border-radius: 2px;
      border: solid 1px #094f91;
      text-align: center;
      // margin-top: 10px;
      cursor: pointer;
      padding-top: 8px;
    }

    .hcqbtn {
      width: 60px;
    }
  }
}
.main_input {
  display: flex;
  // flex-direction: row;
  padding: 10px 20px 10px 20px;
  align-items: center;
  justify-content: space-around;
  .i_danwei {
    // padding: 0 20px;
  }
}
.main_input /deep/ .el-color-picker__icon,
.main_input /deep/ .el-input,
.main_input /deep/ .el-textarea {
  display: inline-block;
  width: 80%;
}

.resultContent {
  .resultTabs {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin: 18px 0;
  }

  .guanxianResult,
  .jiancedianResult {
    font-family: SourceHanSansCN-Medium;
    font-size: 12px;
    font-weight: bold;
    font-stretch: normal;
    line-height: 22px;
    letter-spacing: 0px;
    width: auto;
    text-align: center;
    margin: 0 10px;
    color: #c9e9ff;
  }

  .resultActive {
    border-bottom: solid 2px #00baff;
    color: #00baff;
  }

  .guanxianList,
  .jiancedianList,
  .YingXiangQuYuList {
    padding-left: 20px;
    overflow-y: auto;
    // height: 600px;
    margin-right: 10px;

    .resultItemContent {
      overflow-y: auto;
      overflow-x: hidden;
      height: calc(100vh - 540px);
      margin-top: 10px;
      .resultItem {
        cursor: pointer;
      }

      span {
        font-size: 12px;
        font-weight: normal;
        font-stretch: normal;
        line-height: 28px;
        letter-spacing: 1px;
        color: #95b0c2;
      }
    }

    .resultItemContent::-webkit-scrollbar {
      width: 4px;
      height: 1px;
      background: rgba(9, 85, 133, 0.8);
      display: block;
      border-radius: 3px;
    }

    /*滚动条里面小方块*/
    .resultItemContent::-webkit-scrollbar-thumb {
      border-radius: 5px;
      background: #052149;
    }

    /*滚动条里面轨道*/
    .resultItemContent::-webkit-scrollbar-track {
      border-radius: 3px;
      background: transparent;
    }
  }
}

.fun-btn-container {
  display: flex;
  flex-direction: row;
  padding: 20px 20px;
  justify-content: space-around;
}

.fun-item {
  width: 37px;
  height: 37px;
  // background: url("@/assets/oneMap/hcq-line-uncheck.png") no-repeat;
  box-sizing: border-box;
  background-size: 100% 100%;
  cursor: pointer;

  &:nth-child(1) {
    background: url("@/assets/oneMap/hz-Circle-uncheck.png") no-repeat;
  }

  &:nth-child(2) {
    background: url("@/assets/oneMap/hz-DuoBianXing-uncheck.png") no-repeat;
  }

  &:nth-child(3) {
    background: url("@/assets/oneMap/hz-JuXing-uncheck.png") no-repeat;
  }
}

.checkbox-btn-container {
  padding: 10px 10px;
  text-align: center;
}

.spatial_main_con {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.spatial_main_title {
  width: 280px;
  height: 35px;
  box-sizing: border-box;
  background: url("@/assets/panelTree/dtml_bg_title.png") no-repeat;
  font-family: SourceHanSansCN-Regular;
  font-size: 18px;
  background-size: 100% 100%;
  text-align: left;
  padding-left: 50px;
  line-height: 34px;
  // background-color: red;
  margin: 10px 0 0 10px;
}

.spatial_main_title span {
  font-family: SourceHanSansCN-Regular;
  font-size: 14px;
  color: #c8e9ff;
}

.form_item_title {
  width: 300px;
  height: 16px;
  background: url("@/assets/rightMenu/selectInfo/monitor_form_title.png") 0px
    2px no-repeat;
  text-align: center;
  color: #00baff;
  margin-bottom: 20px;
}

.form_item_title span {
  font-family: SourceHanSansCN-Regular;
  font-size: 14px;
  line-height: 12px;
}

.spatial_result {
  flex: 1;
  padding: 0 10px;
}

.boundary_line {
  width: 289px;
  height: 1px;
  background: url(@/assets/rightMenu/selectInfo/boundary_line.png);
  background-size: 100% 100%;
  margin-bottom: 20px;
}

::v-deep {
  //表单项
  .el-form-item {
    margin-bottom: 6px;
    padding: 0 20px;
  }

  .el-form-item__label {
    font-family: SourceHanSansCN-Regular !important;
    font-size: 14px !important;
    line-height: 44px !important;
    color: #daf0ff !important;
    padding: 0 0 0 16px !important;
  }

  .el-radio,
  .el-checkbox {
    color: #daf0ff;
  }

  .el-table th {
    background-color: #053c6a;
    // border: 1px solid #2b7cb5;
    color: #fff;
  }

  .el-table .el-table__cell {
    padding: 4px 0px !important;
  }

  //鼠标悬停行样式
  .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background: red;
  }

  .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #f6d604 !important;
    /* color: #f19944; */
    /* 设置文字颜色，可以选择不设置 */
  }

  .el-table tr {
    color: #9ca6af;
  }

  .el-table tr:nth-child(2n) {
    background-color: #022546;
  }

  .el-table tr:nth-child(2n + 1) {
    background-color: #1b3c59;
  }

  .el-table--border,
  .el-table--group {
    border: 1px solid rgba(38, 122, 182, 0.9);
  }

  .el-table td.el-table__cell,
  .el-table th.el-table__cell.is-leaf {
    border: 1px solid rgba(38, 122, 182, 0.9);
  }

  .el-table th.el-table__cell > .cell {
    text-align: center;
  }

  // .el-table__body-wrapper::-webkit-scrollbar {
  //     width: 4px;
  //     height: 1px;
  //     background: rgba(9, 85, 133, 0.4);
  //     display: block;
  //     border-radius: 3px;
  // }

  // // // /*滚动条里面小方块*/
  // .el-table__body-wrapper::-webkit-scrollbar-thumb {
  //     border-radius: 5px;
  //     background: #095585;
  // }

  // // // /*滚动条里面轨道*/
  // .el-table__body-wrapper::-webkit-scrollbar-track {
  //     border-radius: 3px;
  //     background: transparent;
  // }
}
</style>
